# -*- coding: utf-8 -*-
# @Time    : 2022/6/23 14:59
# @Author  : zyw
# @Email   : panda_kings@163.com
# @File    : course.py
import json
from flask import Blueprint,jsonify, request
from flask_restful import Api,Resource, marshal,reqparse
from common.models.courses import *
from common.models.users import UserModels,VipModel
from common.model_fields.course_fields import *
from common.models.permissiones import Roles
from common.utils.login_jwt import login_required
from common.utils.jwt_utils import verify_jwt


course_bp = Blueprint('course',__name__, url_prefix='/course')

api = Api(course_bp)


class GetTag(Resource):
    def get(self):
        """获取课程标签"""
        try:
            tag = CourseTag.query.all()

            data = marshal(tag,tag_fields)
            return jsonify(msg='获取成功', code=200, data=data)
            # return marshal(tag, tag_fields)
        except Exception as e:
            return jsonify(msg="获取标签失败",code=500)


class CoursesResource(Resource):
    def get(self):
        """获取所有的课程"""
        parser = reqparse.RequestParser()
        params = ['page', 'size', 'tag_id', 'free', 'online', 'sort']
        for data in params:
            parser.add_argument(data)
        args = parser.parse_args()
        tag_id = args.get('tag_id')
        free = args.get('free')
        online = args.get('online')
        sort = args.get('sort')
        print("tag_id的值%s, online的值%s, free的值%s,sort的值%s" % (tag_id, online, free, sort))
        if free == '免费':
            free = 1
        if free == '限免':
            free = 2
        if free == '免费':
            free = 3
        # 默认获取全部数据
        course_and_tag = CourseandTag.query.all()

        temp = []
        # 标签不为空
        if tag_id != "":
            # 获取中间表
            course_and_tag = CourseandTag.query.filter_by(tag_id=int(tag_id)).all()
        for i in course_and_tag:
            # 获取课程信息
            course = Course.query.filter_by(id=i.course_id).first()
            print('...',course)
            # 类型过滤
            if free != '':
                if free != course.course_type:
                    continue
            # 状态过滤
            if online != '':
                if int(online) != course.course_status:
                    continue

            course = marshal(course,course_fields)
            course = json.loads(json.dumps(course))
            print('course---->', course)
            # # 添加类型名
            type_data = CourseType.query.filter_by(id=course['course_type']).first()
            course["title"] = type_data.title
            temp.append(course)

        # 排序
        if sort != '':
            temp = self.order_data(sort,temp)
        return jsonify(data=temp)

    @staticmethod
    def order_data(order,data):
        if order == 2:
            # 热门排序
            new_data = sorted(data, key=lambda x: x['attention'], reverse=True)
        else:
            # 最新排序
            new_data = sorted(data, key=lambda x: x['create_time'], reverse=True)
        return new_data


class CourseInfoResource(Resource):

    # 强制登录
    @login_required
    def get(self):
        """根据课程id 获取课程信息"""
        parser = reqparse.RequestParser()
        parser.add_argument('cid')
        args = parser.parse_args()
        cid = args.get('cid')
        # TODO 获取当前登录的用户id,
        # 判断当前用户的级别,若不是会员, 没有权限请先升级成为会员
        try:
            vip = VipModel.query.filter_by(user=g.user_id).first()
        except Exception as e:
            return jsonify(message="用户不存在", code=401)
        # 会员用户可以观看免费的,普通用户只能观看免费的视频
        # role_id = vip.level # 当前用户的等级
        # 获取当前用户等级的权限
        role = Roles.query.filter_by(id=vip.level).first()
        # 是权限的列表
        permissons = role.permission
        # 获取当前请求的url
        if str(request.url) not in permissons:
            return jsonify(message="没有权限,请升级会员", code=403)
        # 获取课程
        course = Course.query.filter_by(id=int(cid)).first()
        # 有序字段转换成dict
        order_dict_course = marshal(course,course_fields)
        course_ser = json.loads(json.dumps(order_dict_course))
        # 获取章节
        chapters = Chapters.query.filter_by(course=course.id).all()
        # 序列化
        order_dict_chapter = marshal(chapters,chapter_fields)
        # 章节的字典
        chapters_dict = json.loads(json.dumps(order_dict_chapter))
        # 根据章节获取每个章节下的小节
        # print("章节信息>>>", chapters_dict)
        for i in chapters_dict:
            # 根据章节id获取小节
            sections = Sections.query.filter_by(chapters=i['id']).all()
            # 序列化
            sections_dict = json.loads(json.dumps(marshal(sections, sections_fields)))
            i['sections_list'] = sections_dict
        data_ = {
            'course_ser':course_ser,
            'chapters_dict': chapters_dict
        }
        return jsonify(data=data_, code=200, message="获取成功")


class VideoResource(Resource):
    @login_required
    def get(self):
        """根据小节id获取视频地址"""
        parser = reqparse.RequestParser()
        parser.add_argument('sid')
        args = parser.parse_args()
        sid = args.get('sid')
        # 获取视频地址
        section = Sections.query.filter_by(id=sid).first()
        return jsonify(message='获取成功', data={'video_url':section.video_url})


class CourseAttention(Resource):
    def put(self):
        """更新课程的关注状态"""
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        parser.add_argument('cid')
        # parser.add_argument('is_attention')
        args = parser.parse_args()
        token = args.get('token')
        cid = args.get('cid')
        # is_attention = args.get('is_attention')
        print('前端传来的值:------>', token, cid)
        if token:
            # 校验token
            token_ = token[4:]
            try:
                payload = verify_jwt(token_)
            except Exception as e:
                return  jsonify(message="请先登录", code=401)
            # 获取用户id
            # user_id = payload['user_id']
            try:
                course = Course.query.filter_by(id=cid).first()
                if course.is_attention == 1:
                    # 取消关注
                    Course.query.filter_by(id=cid).update({'is_attention':0, 'attention':course.attention-1})
                    db.session.commit()
                    return jsonify(message="取消关注成功", code=200, data={'attention': course.attention})
                else:
                    # 关注
                    Course.query.filter_by(id=cid).update({'is_attention': 1, 'attention': course.attention +1})
                    db.session.commit()
                    return jsonify(message="关注成功", code=200, data={'attention': course.attention})

            except Exception as e:
                return jsonify(message="服务端错误", code=500)


class CourseLearnStatus(Resource):
    def get(self):
        """获取用户学习进度"""
        parser = reqparse.RequestParser()
        parser.add_argument('token')
        parser.add_argument('cid')
        args = parser.parse_args()
        token = args.get('token')
        cid = args.get('cid')
        if token:
            # 校验token
            token_ = token[4:]
            try:
                payload = verify_jwt(token_)
            except Exception as e:
                return  jsonify(message="请先登录", code=401)
            user_id= payload['user_id']
        # 获取课程额章节
        course_chapters = Chapters.query.filter_by(course=cid).all()

        # 序列化输出
        course_chapters = json.loads(json.dumps(marshal(course_chapters, chapter_fields)))
        # TODO 获取每个章节下的小节信息.需要保存的是学过的小节信息
        data_ = [] # 存放学过的章节
        """
        [
            {
                'id':1,
                'chapter_title':"环境搭建",
                'sections_list':[
                    {
                        'id': 小结1,
                        'title':小节名
                    }
                ]
            }
        ]
        """
        for chapter in course_chapters:
            # 获取小节
            sections = Sections.query.filter_by(chapters=chapters.id, is_learned=1).all()
            # TODO 章节下所有的小节数和学过的小节数对比, 值一样说明章节学完, 否则没学完
            if len(chapter.sections) == len(sections):
                sections = json.loads(json.dumps(marshal(sections, sections_fields)))
                chapter['sections_list'] = sections
                data_.append(chapter)

        return jsonify(message='ok', data=data_)




api.add_resource(GetTag, '/all')
api.add_resource(CoursesResource, '/get_course')
api.add_resource(CourseInfoResource,'/courseinfo')
api.add_resource(VideoResource,'/sectionvideo')
api.add_resource(CourseAttention,'/is_attention')
api.add_resource(CourseLearnStatus,'/learninfo')
